package com.tancire.web.controller.open;

import com.tancire.common.constant.BnsConst;
import com.tancire.common.constant.OpenConst;
import com.tancire.common.core.controller.BaseController;
import com.tancire.common.core.domain.AjaxResult;
import com.tancire.common.core.redis.RedisCache;
import com.tancire.common.utils.StringUtils;
import com.tancire.net.domain.AuthDetail;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 资源开放调用校验接口
 *
 */
@RestController
@RequestMapping("/net/open")
public class OpenNetController extends BaseController {

    @Resource
    private RedisCache redisCache;

    /**
     * 获取会员管理详细信息
     */
    @PostMapping(value = "/check")
    public AjaxResult authByCode(@RequestBody AuthDetail authDetail) {
        Map<String, Object> res = new HashMap<>();
        // 简单校验
        String sourceCode = authDetail.getSourceCode();
        String secret = authDetail.getSecret();
        if (StringUtils.isBlank(sourceCode)) {
            res.put("code", OpenConst.ERROR_CODE);
            res.put("msg", "资源机器码不能为空");
            return AjaxResult.success("校验失败", res);
        }
        if (StringUtils.isBlank(secret)) {
            res.put("code", OpenConst.ERROR_CODE);
            res.put("msg", "资源激活码不能为空");
            return AjaxResult.success("校验失败", res);
        }
        // 捕获异常，全局抛出
        try {
            String code = redisCache.getCacheObject(BnsConst.CALL_SIMPLE_KEY + secret);
            if (sourceCode.equals(code)) {
                res.put("code", OpenConst.SUCCESS_CODE);
                res.put("msg", "资源校验成功");
                Date date = new Date();
                long time = date.getTime();
                time = time + OpenConst.CHECK_TIMEOUT_LONG;
                res.put("data", time);
                return AjaxResult.success("校验成功", res);
            }
        } catch (Exception e) {
            res.put("code", OpenConst.NOT_FOUND_CODE);
            res.put("msg", "获取资源信息失败");
            return AjaxResult.success("校验失败", res);
        }
        return AjaxResult.success("校验成功", res);
    }

}
